package com.stenio.fancat.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

public class XmlUtil {

    private static final Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    public static String fromBean(Object o) {
        XStream xStream = new XStream(new XppDriver(new NoNameCoder()));
        xStream.autodetectAnnotations(true);
        xStream.alias("xml", o.getClass());
        return xStream.toXML(o);
    }

    public static <T> T toBean(String xml, Class<T> clazz) throws IllegalAccessException, InstantiationException {
        XStream xStream = new XStream(new XppDriver(new NoNameCoder()));
        xStream.alias("xml", clazz);
        return (T) xStream.fromXML(xml, clazz.newInstance());
    }

    /**
     * 将请求参数转换为xml格式的string
     * @param parameters
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set<Map.Entry<Object, Object>> es = parameters.entrySet();
        Iterator<Map.Entry<Object, Object>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
            String k = (String) entry.getKey();
            String v = entry.getValue() + "";
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
}
